//
//  FiveMatchViewController.m
//  PlayBall
//
//  Created by yanxun on 8/20/14.
//
//

#import "FiveMatchViewController.h"
#import "JddViewControllerManager.h"
@interface FiveMatchViewController ()<UIWebViewDelegate>{
    NSString *_wapUrl;
    UIActivityIndicatorView *_activityIndicatorView;
    BOOL flag;
    UIWebView *_webView;
    NSMutableURLRequest *_request;
    BOOL _Cookieflag;
}

@end

@implementation FiveMatchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = UIColorRef(234,114,68);
    if (_webView) {
        _webView.delegate = nil;
        _webView = nil;
    }
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-49)];
    _webView.delegate = self;
    _webView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: _webView];
    
    if (IOS7) {
        _webView.frame = CGRectMake(0, 20, 320, self.view.frame.size.height-49-20);
    }
    
    _activityIndicatorView = [[UIActivityIndicatorView alloc]
                              initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)] ;
    //_activityIndicatorView.backgroundColor = [UIColor clearColor];
    [_activityIndicatorView setCenter:self.view.center] ;
    [_activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray] ;
    //[self.view addSubview:_activityIndicatorView] ;
    [_activityIndicatorView startAnimating];
    
    flag = NO;
    
    if ([JddCommonFunction isLogin]) {
        _Cookieflag = YES;
    }else{
        _Cookieflag = NO;
    }
    
    /*
    if (![JddCommonFunction isLogin]) {
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
    }
    */
    //发送请求数据
    //[self fiveMatchRequest];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"FiveMatch"];
    [self setJddTabBarHidden:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [MobClick beginLogPageView:@"FiveMatch"];

    [[self navigationController] setNavigationBarHidden:YES];
    
    [self.view setUserInteractionEnabled:YES];
    
    //显示tabbar
    [self setJddTabBarHidden:NO];
    
    //[self setTabBarItemSelect:2];
    [self fiveMatchRequest];
    
}

//发送五联赛请求
- (void)fiveMatchRequest {
	FiveMatchOperation *operation = [[FiveMatchOperation alloc] init];
	operation.delegate = self;
	[[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}


//清除cookies
-(void) clearHttpCookie{
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
}


//清除UIWebView的缓存
- (void)clearWebViewCache{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

//五大联赛返回结果
- (void)FiveMatchResult:(NSData *)result
{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        id info = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
        //NSLog(@"%@",info);
        _wapUrl = [[info[@"Data"] objectFromJSONString] objectForKey:@"wapurl"];
        if (_wapUrl && ![_wapUrl isKindOfClass:[NSNull class]]) {
            
            
            NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:_wapUrl]];
            NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
            if ([JddCommonFunction isLogin]) {
                for (NSHTTPCookie *cookie in [cookieJar cookies]) {
                    //NSLog(@"\n%@\n", cookie);
                    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie]; //保存
                    NSString *cookieString = [NSString stringWithFormat:@"%@=%@", [cookie name], [cookie value]];
                    [request setValue:cookieString forHTTPHeaderField:@"Cookie"];
                }
                
            }else{
                [self clearHttpCookie];
                [self clearWebViewCache];
                
            }
            _request = request;
            [_webView loadRequest:request];
        }
        
        
        
        [self setJddTabBarHidden:NO];
        /*
        int start = cookies_tmp.indexOf("expires=");
        if(start > 0) {
            int end = cookies_tmp.indexOf(";", start + 1);
            if(end > start) {
                cookies_tmp = cookies_tmp.substring(0, start) + "expires=Fri, 10-Aug-1900 09:18:39 GMT" + cookies_tmp.substring(end);
            }
        }
        */
        
    }
}
//- (void)FiveMatchResult

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationTyp
{
    [_activityIndicatorView stopAnimating];
    [_activityIndicatorView removeFromSuperview];
    //NSLog(@"%@",request.mainDocumentURL.relativePath);
    //[request.mainDocumentURL.relativePath isEqualToString:@"/app/demo.html1|100_60|1"];
    NSString *currentURL = request.mainDocumentURL.relativePath;
    //NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    //NSLog(@"shouldStartLoadWithRequest %@",currentURL);
    /*
    NSRange range1 = [currentURL rangeOfString:@"go/tuijian/index"];//判断字符串是否包含
    NSRange range2 = [currentURL rangeOfString:@"ui-state=dialog"];
    //if (range.location ==NSNotFound)//不包含
    if ((range1.length >0) && (range2.length <= 0))//包含
    {
        //登录
        if (![JddCommonFunction isLogin]) {
            
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN
                                                                    fromController:self
                                                                        withObject:nil
                                                                       withObject2:nil];
            
            
            //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:currentURL]];
            
        }else{
            [self setJddTabBarHidden:NO];
            [[self navigationController] setNavigationBarHidden:YES];
        }
    }
    else//不包含
    {
        
    }
    */
    
    
    
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
}




- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"webViewDidFinishLoad");
    [_activityIndicatorView stopAnimating];
    [_activityIndicatorView removeFromSuperview];
    
    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    NSLog(@"shouldStartLoadWithRequest %@",currentURL);
    
    NSRange range1 = [currentURL rangeOfString:@"login=ios"];//判断字符串是否包含
    //NSRange range2 = [currentURL rangeOfString:@"ui-state=dialog"];
    //if (range.location ==NSNotFound)//不包含
    if ((range1.length >0) )//包含
    {
        //登录
        if (![JddCommonFunction isLogin]) {
            
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN
                                                                    fromController:self
                                                                        withObject:nil
                                                                       withObject2:nil];
            
        }else{
            
        }
    }
    else//不包含
    {
        
    }
    
    //NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    //NSLog(@"%@",currentURL);
    
    //NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    //NSLog(@"webViewDidFinishLoad %@",currentURL);
    
    //NSLog(@"navarr = %@",self.navigationController.viewControllers);
    
    
    
    
    //[self setJddTabBarHidden:NO];
    //[[self navigationController] setNavigationBarHidden:YES];
    // NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    //NSLog(@"%@",currentURL);
    /*
    [_webView stringByEvaluatingJavaScriptFromString:@""];
    
    if (![[_webView stringByEvaluatingJavaScriptFromString:@"typeof WebViewJavascriptBridge == 'window.jdd.doLogin()'"] isEqualToString:@"true"]) {
        NSLog(@"登录");
        //NSString *filePath = [[NSBundle mainBundle] pathForResource:@"WebViewJavascriptBridge.js" ofType:@"txt"];
        //NSString *js = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        //[_webView stringByEvaluatingJavaScriptFromString:js];
    }
    
    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    NSRange foundObj=[currentURL rangeOfString:@"interface/pay/wap/WapAlipayReturn.jsp" options:NSCaseInsensitiveSearch];
    NSLog(@"webViewDidFinishLoad---currentURL==%@",currentURL);
    if((foundObj.length>0) && !flag) {
        //flag 防止点击多次完成，导致多次推送
        flag = YES;
        //[self pushRequest];
    }
     */
    

    /*
    NSString *urlString = [[_request URL] absoluteString];
    urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"urlString=%@",urlString);
    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
    if([urlComps count] && [[urlComps objectAtIndex:0] isEqualToString:@"objc"])
    {
        
        NSArray *arrFucnameAndParameter = [(NSString*)[urlComps objectAtIndex:1] componentsSeparatedByString:@":/"];
        NSString *funcStr = [arrFucnameAndParameter objectAtIndex:0];
        
        if (1 == [arrFucnameAndParameter count])
        {
            // 没有参数
            if([funcStr isEqualToString:@"doFunc1"])
            {
                
                //调用本地函数1
                NSLog(@"doFunc1");
                
            }
        }
        else
        {
            //有参数的
            if([funcStr isEqualToString:@"getParam1:withParam2:"])
            {
                //[self getParam1:[arrFucnameAndParameter objectAtIndex:1] withParam2:[arrFucnameAndParameter objectAtIndex:2]];
            }
        }
        //return NO;
    }
    */
    //return TRUE;
    //[self setJddTabBarHidden:NO];
    //[[self navigationController] setNavigationBarHidden:YES];
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription]  delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alterview show];
}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
